package org.monkey.socket.plugin.provider;

import java.util.ArrayList;
import java.util.List;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.monkey.common.constant.util.ProtostuffUtil;
import org.monkey.socket.plugin.entity.SocketMsg;
import org.monkey.socket.plugin.service.IMsgAcceptFailedHandler;
import org.monkey.socket.plugin.service.IMsgAcceptHandler;

/**
 * 广播消息处理器 用于处理广播而来的消息 一般不需要重写
 */
@Data
@Slf4j
public final class MsgAcceptProvider {

  private List<IMsgAcceptHandler> acceptHandlers;
  private IMsgAcceptFailedHandler msgAcceptFailedHandler;

  public MsgAcceptProvider(
      IMsgAcceptFailedHandler msgAcceptFailedHandler) {
    this.msgAcceptFailedHandler = msgAcceptFailedHandler;
  }

  public void onMessage(byte[] msg) {
    log.info("accept publish msg:{}", msg);
    SocketMsg socketMsg = null;
    try {
      socketMsg = ProtostuffUtil.deserialize(msg, SocketMsg.class);
    } catch (Exception e) {
      log.error("deserialize msg failed:msg text={},", msg, e);
    }
    if (acceptHandlers != null) {
      boolean next = true;
      try {
        for (IMsgAcceptHandler acceptHandler : acceptHandlers) {
          if (socketMsg != null && next) {
            next = acceptHandler.acceptHandle(socketMsg);
          }
        }
      } catch (Exception e) {
        log.error("msg accepted deal failed,msg={},", socketMsg, e);
        if (msgAcceptFailedHandler != null) {
          msgAcceptFailedHandler.acceptFailedHandle(socketMsg, e);
        }
      }
    }
  }

  public MsgAcceptProvider addAcceptHandler(IMsgAcceptHandler iMsgAcceptHandler) {
    if (acceptHandlers == null) {
      acceptHandlers = new ArrayList<>();
    }
    acceptHandlers.add(iMsgAcceptHandler);
    return this;
  }

}
